<template>
  <div class="project-list p-4">
    <el-card class="box-card">
      <template #header>
        <div class="card-header flex items-center justify-between">
          <h2 class="text-xl font-bold">项目列表</h2>
          <el-button type="primary" @click="goToCreate">创建项目</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-container mb-4 flex flex-wrap items-center gap-4">
        <el-input
          v-model="queryParams.keyword"
          placeholder="项目名称/描述"
          class="w-64"
          clearable
          @clear="handleQuery"
        />
        
        <el-select v-model="queryParams.type" placeholder="项目类型" clearable @change="handleQuery" class="w-32">
          <el-option label="前端" :value="ProjectType.FRONTEND" />
          <el-option label="后端" :value="ProjectType.BACKEND" />
        </el-select>
        
        <el-select v-model="queryParams.status" placeholder="项目状态" clearable @change="handleQuery" class="w-32">
          <el-option label="开发中" :value="ProjectStatus.DEVELOPMENT" />
          <el-option label="激活" :value="ProjectStatus.ACTIVE" />
          <el-option label="非活跃" :value="ProjectStatus.INACTIVE" />
          <el-option label="已废弃" :value="ProjectStatus.DEPRECATED" />
        </el-select>
        
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="projectList"
        stripe
        border
        style="width: 100%"
        row-key="id"
        :expand-row-keys="expandRowKeys"
        @expand-change="handleExpandChange"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="p-4 bg-gray-50">
              <h3 class="font-bold mb-2">启动脚本:</h3>
              <el-input
                v-model="row.startup_script"
                type="textarea"
                :rows="5"
                placeholder="暂无启动脚本"
                readonly
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="项目名称" width="180" show-overflow-tooltip />
        <el-table-column label="项目类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === ProjectType.FRONTEND ? 'success' : 'info'">
              {{ row.type === ProjectType.FRONTEND ? '前端' : '后端' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="项目描述" show-overflow-tooltip />
        <el-table-column label="项目状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="450" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="goToDetail(row.id)">详情</el-button>
            <el-button type="primary" link @click="goToEdit(row.id)">编辑</el-button>
            <el-button type="primary" link @click="handleConfig(row)">配置项</el-button>
            <el-button type="primary" link @click="handleVersion(row)">版本</el-button>
            <el-button type="primary" link @click="handleDeploy(row)">部署</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container mt-4 flex justify-end">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.page_size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 部署对话框 -->
    <el-dialog v-model="deployDialogVisible" title="部署项目" width="500px">
      <el-form :model="deployForm" label-width="100px" :rules="deployRules">
        <el-form-item label="项目名称">
          <span>{{ deployForm.projectName }}</span>
        </el-form-item>
        <el-form-item label="环境" prop="environment">
          <el-select v-model="deployForm.environment" placeholder="请选择部署环境" class="w-full">
            <el-option label="开发环境" value="development" />
            <el-option label="测试环境" value="test" />
            <el-option label="预生产环境" value="staging" />
            <el-option label="生产环境" value="production" />
          </el-select>
        </el-form-item>
        <el-form-item label="部署路径" prop="deployPath">
          <el-input v-model="deployForm.deployPath" placeholder="可选，如 /var/www/html" />
        </el-form-item>
        <el-form-item label="部署人" prop="deployedBy">
          <el-input v-model="deployForm.deployedBy" placeholder="可选填写部署人" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deployDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDeploy" :loading="deployLoading">确认部署</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 脚本对话框 -->
    <el-dialog v-model="scriptDialogVisible" title="项目脚本" width="800px">
      <el-form>
        <el-form-item label="项目名称">
          <span>{{ currentProject?.name || '' }}</span>
        </el-form-item>
        <el-form-item label="脚本内容">
          <el-input
            v-model="scriptContent"
            type="textarea"
            :rows="15"
            placeholder="输入项目脚本内容"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="scriptDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveScript" :loading="scriptLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getProjectList, 
  deleteProject, 
  createDeployment,
  getProjectScript,
  updateProjectScript
} from '@/request/project-api'
import { ProjectType, ProjectStatus, type Project } from '@/model/project-model'
import type { PageQuery } from '@/model/common-model'

defineOptions({
  name: 'ProjectList'
})

const router = useRouter()
const loading = ref(false)
const projectList = ref<Project[]>([])
const total = ref(0)
const expandRowKeys = ref<(string | number)[]>([])

// 查询参数
const queryParams = reactive<PageQuery>({
  page: 1,
  page_size: 10,
  keyword: '',
  type: undefined,
  status: undefined
})

// 部署对话框相关
const deployDialogVisible = ref(false)
const deployLoading = ref(false)
const deployForm = reactive({
  projectId: 0,
  projectName: '',
  environment: 'development',
  deployPath: '',
  deployedBy: ''
})

// 部署表单验证规则
const deployRules = {
  environment: [
    { required: true, message: '请选择部署环境', trigger: 'change' }
  ]
}

// 脚本对话框相关
const scriptDialogVisible = ref(false)
const scriptLoading = ref(false)
const scriptContent = ref('')
const currentProject = ref<Project | null>(null)



// 获取项目列表
const getList = async () => {
  loading.value = true
  try {
    // 恢复使用包含分页参数的请求
    // 使用queryParams对象，它已经包含了page和page_size
    console.log('请求API带分页参数', queryParams)
    const response = await getProjectList(queryParams)
    console.log('API响应:', response)
    if (response.code === 0) {
      projectList.value = response.data
      total.value = response.total || 0
    } else {
      ElMessage.error(response.errorMsg || '获取项目列表失败')
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.page = 1
  queryParams.page_size = 10
  queryParams.keyword = ''
  queryParams.type = undefined
  queryParams.status = undefined
  getList()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  queryParams.page_size = val
  getList()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  queryParams.page = val
  getList()
}

// 获取状态标签类型
const getStatusTag = (status: ProjectStatus): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  switch (status) {
    case ProjectStatus.ACTIVE:
      return 'success'
    case ProjectStatus.DEVELOPMENT:
      return 'info'
    case ProjectStatus.DEPRECATED:
      return 'danger'
    case ProjectStatus.INACTIVE:
      return 'warning'
    default:
      return 'info'
  }
}

// 获取项目状态中文描述
const getProjectStatusText = (status?: ProjectStatus): string => {
  if (!status) return '未知状态'
  
  switch (status) {
    case ProjectStatus.ACTIVE:
      return '活跃'
    case ProjectStatus.DEVELOPMENT:
      return '开发中'
    case ProjectStatus.DEPRECATED:
      return '已废弃'
    case ProjectStatus.INACTIVE:
      return '非活跃'
    default:
      return '未知状态'
  }
}

// 获取状态名称
const getStatusName = (status: ProjectStatus) => {
  switch (status) {
    case ProjectStatus.ACTIVE:
      return '激活'
    case ProjectStatus.INACTIVE:
      return '非活跃'
    case ProjectStatus.DEVELOPMENT:
      return '开发中'
    case ProjectStatus.DEPRECATED:
      return '已废弃'
    default:
      return status
  }
}

// 跳转到创建页面
const goToCreate = () => {
  router.push('/project/create')
}

// 跳转到详情页面
const goToDetail = (id: number) => {
  router.push(`/project/detail/${id}`)
}

// 跳转到编辑页面
const goToEdit = (id: number) => {
  router.push(`/project/edit/${id}`)
}

// 处理删除
const handleDelete = (row: Project) => {
  ElMessageBox.confirm(`确认删除项目 "${row.name}" 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        // 确保id是数字类型
        const response = await deleteProject(Number(row.id))
        if (response.code === 0) {
          ElMessage.success('删除成功')
          getList()
        } else {
          ElMessage.error(response.errorMsg || '删除失败')
        }
      } catch (error) {
        console.error('删除项目失败:', error)
        ElMessage.error('删除项目失败')
      }
    })
    .catch(() => {
      // 取消删除操作
    })
}

// 处理配置项
const handleConfig = (row: Project) => {
  router.push(`/project/config/${row.id}`)
}

// 处理配置文件
const handleConfigFiles = (row: Project) => {
  router.push(`/project/config-files/${row.id}`)
}

// 处理版本管理
const handleVersion = (row: Project) => {
  router.push(`/project/version/${row.id}`)
}

// 处理脚本
const handleScript = async (row: Project) => {
  try {
    currentProject.value = row
    scriptLoading.value = true
    scriptDialogVisible.value = true
    
    // 获取项目脚本
    const response = await getProjectScript(row.id)
    if (response.code === 0 && response.data) {
      scriptContent.value = response.data.content || ''
    } else {
      // 如果没有脚本数据或返回错误，设置为空
      scriptContent.value = ''
    }
  } catch (error) {
    console.error('获取项目脚本失败:', error)
    ElMessage.error('获取项目脚本失败')
    scriptContent.value = ''
  } finally {
    scriptLoading.value = false
  }
}

// 保存脚本
const saveScript = async () => {
  if (!currentProject.value) return
  
  try {
    scriptLoading.value = true
    const response = await updateProjectScript(currentProject.value.id, scriptContent.value)
    if (response.code === 0) {
      ElMessage.success('脚本保存成功')
      scriptDialogVisible.value = false
    } else {
      ElMessage.error(response.errorMsg || '脚本保存失败')
    }
  } catch (error) {
    console.error('保存项目脚本失败:', error)
    ElMessage.error('保存项目脚本失败')
  } finally {
    scriptLoading.value = false
  }
}

// 处理部署
const handleDeploy = (row: Project) => {
  deployForm.projectId = row.id
  deployForm.projectName = row.name
  deployForm.environment = 'development'
  deployDialogVisible.value = true
}

// 确认部署
const confirmDeploy = async () => {
  try {
    deployLoading.value = true
    // 构建部署数据
    const deployData = {
      project_id: Number(deployForm.projectId),
      environment: deployForm.environment,
      deploy_path: deployForm.deployPath || undefined,
      deployed_by: deployForm.deployedBy || undefined
    }
    
    const response = await createDeployment(
      deployData.project_id,
      0, // 默认使用最新版本，如果需要指定版本可以在后续增加版本选择器
      deployData.environment,
      {
        deploy_path: deployData.deploy_path,
        deployed_by: deployData.deployed_by
      }
    )
    
    if (response.code === 0) {
      ElMessage.success('部署成功')
      deployDialogVisible.value = false
      
      // 可选: 显示部署ID或跳转到部署详情页
      if (response.data && response.data.id) {
        ElMessage.info(`部署任务ID: ${response.data.id}`)
        // router.push(`/deployment/detail/${response.data.id}`)
      }
      
      getList() // 刷新项目列表
    } else {
      ElMessage.error(response.errorMsg || '部署失败')
    }
  } catch (error) {
    console.error('部署项目失败:', error)
    ElMessage.error('部署项目失败')
  } finally {
    deployLoading.value = false
  }
}

// 处理展开行的变化
const handleExpandChange = (row: Project, expanded: boolean) => {
  if (expanded) {
    // 只允许展开一行
    expandRowKeys.value = [row.id]
  } else {
    expandRowKeys.value = []
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.search-form {
  margin-bottom: 16px;
}

.config-table-container {
  .el-table {
    --el-table-border-color: #ebeef5;
    --el-table-header-bg-color: #f5f7fa;
  }
  
  .config-table-row {
    font-size: 14px;
  }
  
  .el-tag {
    margin: 0;
  }
}

.project-list {
  .pagination-container {
    padding: 10px 0;
  }
  
  .el-button.el-button--primary.is-link,
  .el-button.el-button--danger.is-link {
    padding: 0 6px;
    margin-right: 0;
  }
}
</style>
